import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda, Compose
import matplotlib.pyplot as plt

"""调用FashionMNIST数据集训练模型
教程：https://pytorch.org/tutorials/beginner/basics/quickstart_tutorial.html
数据集：FashionMNIST(训练集有60000个样本，测试数据集共10000个样本)
模型：self.linear_relu_stack = nn.Sequential()
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=lr)
优化次数:分epochs个周期迭代优化参数;
超参数1：batch_size = 64 lr=1e-3 
训练结果1：
Epoch 1 Test Error:Accuracy: 47.5%, Avg loss: 2.146723
Epoch 5 Test Error:Accuracy: 65.1%, Avg loss: 1.077281
超参数2：batch_size = 64 lr=1e-2 

训练结果1：
Epoch 1 Test Error:Accuracy: 71.7%, Avg loss: 0.790203 
Epoch 5 Test Error:Accuracy: 81.5%, Avg loss: 0.516817 
超参数2：batch_size = 64 lr=1e-1 

训练结果3：
Epoch 1 Test Error:Accuracy: 78.7%, Avg loss: 0.554423 
Epoch 5 Test Error:Accuracy: 85.5%, Avg loss: 0.388309 

超参数4：batch_size = 100 lr=1e-1
训练结果4：
Epoch 1 Test Error:Accuracy: 81.2%, Avg loss: 0.530495
Epoch 5 Test Error:Accuracy: 86.6%, Avg loss: 0.376539 

超参数5：batch_size = 200 lr=1e-1
训练结果5：
Epoch 1 Test Error:Accuracy: 77.4%, Avg loss: 0.620751
Epoch 5 Test Error:Accuracy: 85.2%, Avg loss: 0.413253 

超参数6：batch_size = 100 lr=0.5e-1
训练结果6：
Epoch 1 Test Error:Accuracy:78.4%, Avg loss: 0.605026
Epoch 5 Test Error:Accuracy:85.3%, Avg loss: 0.410651 

超参数7：batch_size = 100 lr=1e-1
训练结果7：
Epoch 1 Test Error:Accuracy: 78.1%, Avg loss: 0.606795
Epoch 19 Test Error:Accuracy: 88.5%, Avg loss: 0.326118 
Epoch 20 Test Error:Accuracy: 88.5%, Avg loss: 0.326118 
"""
batch_size = 64
lr = 1e-1
epochs = 3  # 训练优化次数
# Download training data from open datasets.
training_data = datasets.FashionMNIST(
    root="data",
    train=True,
    download=True,
    transform=ToTensor(),
)

# Download test data from open datasets.
test_data = datasets.FashionMNIST(
    root="data",
    train=False,
    download=True,
    transform=ToTensor(),
)

# Create data loaders.
train_dataloader = DataLoader(training_data, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)

for X, y in train_dataloader:
    """遍历数据（输入，输出）形状
    Out:Shape of X [N, C, H, W]:  torch.Size([64, 1, 28, 28])
    Shape of y:  torch.Size([64]) torch.int64
    """
    print("Shape of X [N, C, H, W]: ", X.shape)
    print("Shape of y: ", y.shape, y.dtype)
    break

"""Creating Models-创建神经网络模型
思路：继承nn.Module"""
# Get cpu or gpu device for training.
device = "cuda" if torch.cuda.is_available() else "cpu"  # 条件判断，gpu是否可用
print("Using {} device".format(device))  # 格式化输出-花括号与圆括号对应


# Define model-定义模型类
class NeuralNetwork(nn.Module):
    def __init__(self):
        super(NeuralNetwork, self).__init__()
        self.flatten = nn.Flatten()  # 降维
        # 构造模型-用序列化容器
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28 * 28, 512),
            nn.ReLU(),
            nn.Linear(512, 512),
            nn.ReLU(),
            nn.Linear(512, 10)
        )

    # 定义前向函数-传输x与返回y
    def forward(self, x):
        x = self.flatten(x)
        logits = self.linear_relu_stack(x)
        return logits


model = NeuralNetwork().to(device)  # 指定模型类处理装置
print(model)

loss_fn = nn.CrossEntropyLoss()
"""Optimizing the Model Parameters-优化模型参数
# 损失函数-交叉熵损失函数
"""
optimizer = torch.optim.SGD(model.parameters(), lr=lr)


# 优化器-模型参数，学习率


def train(dataloader, model, loss_fn, optimizer):
    """定义-训练函数；
    在单个训练循环中，模型对训练数据集进行预测（分批输入），并反向传播预测误差以调整模型参数。
    out：loss: 1.951310  [    0/60000]
    输出：损失，样本位置
    """
    size = len(dataloader.dataset)
    model.train()
    for batch, (X, y) in enumerate(dataloader):
        X, y = X.to(device), y.to(device)

        # Compute prediction error-计算预测误差
        pred = model(X)  # 预测值
        loss = loss_fn(pred, y)

        # Backpropagation-反向传播（自动迭求梯度，迭代优化参数）
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if batch % 100 == 0:  # 64*100=6400
            loss, current = loss.item(), batch * len(X)
            print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")  # 格式化输出：保留有效数字


def test(dataloader, model, loss_fn):
    """定义-测试函数
    out:Test Error: Accuracy: 59.7%, Avg loss: 1.547367
    输出 (精确度，平均损失）
    """
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    model.eval()  # 字符串求值函数：执行一个字符串表达式，并返回表达式的值
    test_loss, correct = 0, 0
    with torch.no_grad():
        for X, y in dataloader:
            X, y = X.to(device), y.to(device)
            pred = model(X)
            test_loss += loss_fn(pred, y).item()  # 测试损失值-求和
            correct += (pred.argmax(1) == y).type(torch.float).sum().item()
    test_loss /= num_batches  # 测试损失值-求平均值
    correct /= size
    print(f"Test Error: \n Accuracy: {(100 * correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")


for t in range(epochs):  # 循环epochs次
    print(f"Epoch {t + 1}\n-------------------------------")
    train(train_dataloader, model, loss_fn, optimizer)
    test(test_dataloader, model, loss_fn)
print("Done!")

#Saving Models-保存模型-保存模型状态字典到指定文件
torch.save(model.state_dict(), "model.pth")
print("Saved PyTorch Model State to model.pth")
#Loading Models-加载模型状态字典文件
model = NeuralNetwork()
model.load_state_dict(torch.load("model.pth"))

classes = [
    "T-shirt/top",
    "Trouser",
    "Pullover",
    "Dress",
    "Coat",
    "Sandal",
    "Shirt",
    "Sneaker",
    "Bag",
    "Ankle boot",
]

model.eval()
#根据模型指定数据进行预测
x, y = test_data[0][0], test_data[0][1]
with torch.no_grad():
    pred = model(x)
    predicted, actual = classes[pred[0].argmax(0)], classes[y]
    print(f'Predicted: "{predicted}", Actual: "{actual}"')